<template>
	<div class="w1024-wrap">
		<div class="page">
			<div class="head" style="margin-bottom: 10px;">
				<div class="search-wrap">
					<div class="clear">
						<div class="form-item left">
							<p class="form-item-title">资源类型：</p>
							<div class="form-item-content" style="width: 120px;">
								<el-select @change="search" clearable v-model="searchData.resourcetype" placeholder="请选择">
									<el-option key="1" label="新资源" value="1"></el-option>
									<el-option key="2" label="回收资源" value="2"></el-option>
								</el-select>
							</div>
						</div>
						<div class="form-item left">
							<p class="form-item-title">客户姓名：</p>
							<div class="form-item-content">
								<el-input clearable v-model="searchData.customername" placeholder="请输入客户姓名"></el-input>
							</div>
						</div>
						<div class="form-item left">
							<p class="form-item-title">客户等级：</p>
							<div class="form-item-content" style="width: 120px;">
								<el-select @change="search" clearable v-model="searchData.customertype" placeholder="请选择">
									<el-option key="1" label="A类客户" value="1"></el-option>
									<el-option key="2" label="B类客户" value="2"></el-option>
									<el-option key="3" label="C类客户" value="3"></el-option>
								</el-select>
							</div>
						</div>
						<div class="form-item left">
							<p class="form-item-title" style="width: 60px;">行业：</p>
							<div class="form-item-content" style="width: 190px;">
								<el-cascader clearable v-model="cascaderValue" ref="cascader" @change="businessChange" style="width:100%" :props="props"></el-cascader>
							</div>
						</div>
					</div>
					<div class="clear">
						<div class="form-item left">
							<p class="form-item-title" style="width: 100px;">入公海时间：</p>
							<div class="form-item-content" style="width: 230px;">
								<el-date-picker clearable style="width:230px;" v-model="value1" value-format="yyyy-MM-dd" type="daterange" @change="giveUpTimeChange" start-placeholder="开始日期" end-placeholder="结束日期" placeholder="选择日期">
								</el-date-picker>
							</div>
						</div>
						<div class="form-item left">
							<el-button class="left" type="primary" @click="search">查询</el-button>
							<el-button class="left" type="default" @click="reset">重置</el-button>
						</div>
						<div class="form-item right" style="margin-right: 0;">
							<el-button class="add-btn" type="primary left" @click="add"><i class="el-icon-plus"></i>新建</el-button>
							<el-button v-if="level==1" class="distribute-btn" type="primary left" @click="importMaterial"><img src="../../assets/images/crm/import.svg" />导入</el-button>
							<el-button class="import-btn" type="primary left" @click="batchGet">批量领取</el-button>
						</div>
					</div>
				</div>
			</div>
			<template v-if="list.length">
				<div class="table-wrap">
					<el-table ref="table" v-loading="loading" size="middle" :data="list" style="width: 100%">
						<el-table-column fixed type="selection" width="36"></el-table-column>
						<el-table-column label="客户姓名" min-width="60">
							<template slot-scope="scope">
								<span>{{scope.row.customername||'-'}}</span>
							</template>
						</el-table-column>
						<el-table-column label="集团名称" min-width="70">
							<template slot-scope="scope">
								<span>{{scope.row.companyname||'-'}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="linkphone" label="联系电话" min-width="80"></el-table-column>
						<el-table-column prop="customerlevel" label="客户类别" min-width="70">
							<template slot-scope="scope">
								<span>{{scope.row.customertype==1?'A类客户':scope.row.customertype==2?'B类客户':scope.row.customertype==3?'C类客户':'-'}}</span>
							</template>
						</el-table-column>
						<el-table-column  label="来源" min-width="56">
							<template slot-scope="scope">
								<span>{{(scope.row.selfbuild==1&&scope.row.isimport==2)?'手动创建':!scope.row.source?'-':scope.row.source==1?'抖音':scope.row.source==2?'快手':'头条'}}</span>
							</template>
						</el-table-column>
						<el-table-column label="行业" min-width="76">
							<template slot-scope="scope">
								<span>{{!scope.row.tradename?'-':scope.row.tradename+(scope.row.tradedetail?'-'+scope.row.tradedetail:'')}}</span>
							</template>
						</el-table-column>
						<el-table-column label="资源类型" min-width="60">
							<template slot-scope="scope">
								<span>{{scope.row.resourcetype==1?'新资源':'回收资源'}}</span>
							</template>
						</el-table-column>
						<el-table-column label="最近跟进记录" min-width="110">
							<template slot-scope="scope">
								<span>{{scope.row.latestmemo||'-'}}</span>
							</template>
						</el-table-column>leavetime
						<el-table-column label="留电时间" width="90">
							<template slot-scope="scope">
								<span>{{scope.row.leavetime||'-'}}</span>
							</template>
						</el-table-column>
						<el-table-column label="入库时间" width="90">
							<template slot-scope="scope">
								<span>{{scope.row.freetime||'-'}}</span>
							</template>
						</el-table-column>
						<el-table-column fixed="right" width="96" label="操作">
							<div slot-scope="scope" class="btn-inner clear">
								<router-link :to="'/crm/materialdetail/'+scope.row.customeruid" class="btn" title="详情">
									<img src="../../assets/images/crm/detail.svg" />
								</router-link>
								<div class="btn" title="编辑" @click="edit(scope.row)">
									<img src="../../assets/images/crm/edit.svg" />
								</div>
								<!--<div class="btn" v-if="(level==1||level==2)&&scope.row.assignstatus==1" title="分配" @click="distribute(scope.row)">
									<img src="../../assets/images/crm/distribute.svg" />
								</div>-->
								<el-popconfirm v-if="level>1&&scope.row.currentuserid!=user.buyerid" confirm-button-text='确定' cancel-button-text='取消' icon="el-icon-info" icon-color="orange" @confirm="get(scope.row.customeruid)" title="确定要领取当前客户吗？">
									<span slot="reference" style="background: #A981D8;" class="btn pay-btn" title="领取">领</span>
								</el-popconfirm>
							</div>
						</el-table-column>
					</el-table>
				</div>
				<el-pagination :current-page="this.searchData.pagenow" class="text-center" layout="prev, pager, next,sizes" prev-text="上一页" next-text="下一页" @size-change="pageSizeChange" @current-change="currentPageChange" :total="totalCount">
				</el-pagination>
			</template>
			<no-data v-if="!loading&&!list.length"></no-data>
		</div>
		
		<el-dialog title="导入" top="30vh" :visible.sync="importVisible" @close="closeUpload" width="420px" center>
			<div class="dialog-content clear" style="padding: 30px 10px;">
				<div class="form-item" >
					<p class="form-item-title">选择文件：</p>
					<div class="form-item-content" style="width: auto;">
						<div class="clear">
							<el-upload :limit="1" style="width:200px;" ref="upload" :auto-upload="false" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" :action="baseUrl+'/api/product/crm/customer/uploadfile'" :http-request="upload" class="upload-demo left" :before-upload="beforeUpload" :on-success="uploadSuccess" :on-error="uploadError">
								<el-button size="small" type="primary"><i class="el-icon-upload"></i>点击选择</el-button>
							</el-upload>
							<a href="https://img.xnhkfpt.com/lvdata/CRM_TEMPLATE.xls" class="left template-download">模板下载</a>
						</div>
						
						<div class="red" style="line-height: 18px;margin-top: 4px;width: 256px;" v-html="tipText"></div>
					</div>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" plain @click="closeUpload">取 消</el-button>
			    <el-button type="primary" @click="confirmImport">确定上传</el-button>
			</span>
		</el-dialog>
		
		<add-or-edit-customer :customerData="obj" :type="2" :show="editVisible" @closeEditCustomer="editVisible=false" @updateSuccess="getData"></add-or-edit-customer>
		<el-dialog :title="batchFlag?'批量分配':'分配'" top="30vh" :visible.sync="distributeVisible" width="360px" center>
			<div class="dialog-content clear" style="padding: 30px 10px;">
				<div class="form-item" >
					<p class="form-item-title">{{level==1?'所属渠道':'所属人'}}：</p>
					<div class="form-item-content">
						<el-select @change="channelChange" clearable v-model="channelIndex" placeholder="请选择">
							<el-option v-for="(item,index) in channelList" :key="item.channelid" :label="item.channelname" :value="index"></el-option>
						</el-select>
					</div>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" plain @click="distributeVisible=false">取 消</el-button>
			    <el-button v-if="!batchFlag" type="primary" @click="confirmDistribute">确 认</el-button>
			    <el-button v-else type="primary" @click="confirmBatchDistribute">确 认</el-button>
			</span>
		</el-dialog>
		
		<input type="hidden" name="" id="" :value="user" />
		<view-img :src="imgSrc" v-if="showImg" @close="closeImg"></view-img>
	</div>
</template>

<script>
	import NoData from '@/components/NoData'
	import AddOrEditCustomer from '@/components/AddOrEditCustomer'
	import { phoneReg, deepClone,baseUrl,setCookie,getCookie} from '@/utils/common'
	export default {
		name: 'Pool',
		components: {
			NoData,
			AddOrEditCustomer,
		},
		data() {
			const that=this
			return {
				baseUrl,
				level:'',
				value1: '',
				loading: false,
				network: false,
				totalCount: 0,
				editVisible:false,
				distributeVisible:false,
				importVisible:false,
				tipText:'',
				cascaderValue:'',
				channelList:[],
				props: {
		          lazy: true,
		          value:'crmconfiguid',
		          label:'name',
		          checkStrictly:true,
		          lazyLoad (node, resolve) {
		            const { level } = node;
		            that.$request.queryConfigList({
		            	type:5,
		            	parentid:level==0?0:node.value
		            }).then(res=>{
		            	if(res.code==0){
		            		res.list.forEach(item=>{
		            			item.leaf=item.parentid>0
		            		})
		            		resolve(res.list)
		            	}
		            	else{
		            		resolve([])
		            	}
		            })
		          }
		        },
				searchData: {
					shownum: 10,
					pagenow: getCookie('page')?Number(getCookie('page')):1,
					category:2,
					customertype:'',
					companyname:'',
					customername:'',
					linkphone:'',
					followstatus:'',
					ownername:'',
					tradename:'',
					tradedetail:'',
					freetimestart:'',
					freetimeend:'',
					resourcetype:'',
					casetype:'',
				},
				list: [],
				obj:{},
				batchFlag:false,
				channelIndex:'',
				customeruids:'',
				distributeObj:{
					customeruid:'',
					channelid:'',
					channelname:'',
				},
			}
		},
		computed:{
			user(){
				if(this.$store.state.user){
					this.level=this.$store.state.user.crmLevel
				}
				return this.$store.state.user
			}
		},
		beforeRouteLeave(to,from,next){
			console.log(to)
			if(to.name=='MaterialDetail'){
				setCookie('page',this.searchData.pagenow,1)
				sessionStorage.setItem('searchData',JSON.stringify({
					type:'pool',
					data:this.searchData
				}))
			}
			next()
		},
		mounted() {
			setCookie('page',0,-1)
			if(sessionStorage.getItem('searchData')){
				var data=JSON.parse(sessionStorage.getItem('searchData'))
				if(data.type=='pool'){
					Object.assign(this.searchData,data.data)
					this.value1=this.searchData.freetimestart&&this.searchData.freetimeend?[this.searchData.freetimestart,this.searchData.freetimeend]:''
				}
				sessionStorage.removeItem('searchData')
			}
			this.getData()
			this.queryChannelList()
		},
		methods: {
			giveUpTimeChange(val) {
				if(val) {
					this.searchData.freetimestart = val[0]
					this.searchData.freetimeend = val[1]
				} else {
					this.searchData.freetimestart = ''
					this.searchData.freetimeend = ''
				}
			},
			pageSizeChange(pageSize) {
				this.searchData.shownum = pageSize
				this.getData()
			},
			currentPageChange(page) {
				this.searchData.pagenow = page
				this.getData()
			},
			queryChannelList(){
				this.$request.queryChannelList()
				.then(res=>{
					if(res.code==0){
						this.channelList=res.list||[]
					}
				})
			},
			search() {
				this.searchData.pagenow = 1
				this.getData()
			},
			reset() {
				this.searchData = {
					shownum: 10,
					pagenow: 1,
					category:2,
					customertype:'',
					companyname:'',
					customername:'',
					linkphone:'',
					followstatus:'',
					ownername:'',
					tradename:'',
					tradedetail:'',
					freetimestart:'',
					freetimeend:'',
					resourcetype:'',
					casetype:'',
				}
				this.value1=''
				this.cascaderValue=''
				this.getData()
			},
			businessChange(val){
				var result=this.$refs.cascader.getCheckedNodes()[0]
				if(result){
					if(result.path.length==1){
						this.searchData.tradename=result.pathLabels[0]
					}else{
						this.searchData.tradename=result.pathLabels[0]
						this.searchData.tradedetail=result.pathLabels[1]
					}
				}
				else{
					this.searchData.tradename=''
					this.searchData.tradedetail=''
				}
				this.$refs.cascader.dropDownVisible = false;
				this.search()
			},
			getData() {
				this.loading = true
				console.log(this.searchData)
				this.$request.queryCustomerList(this.searchData)
					.then(res => {
						if(res.code == 0) {
							this.list = res.list
							this.totalCount = res.page.totalresult
						} else {
							this.msgError(res.msg)
						}
						this.loading = false
					})
			},
			add() {
				this.obj={}
				this.editVisible=true
			},
			
			importMaterial() {
				this.tipText=''
				this.importVisible=true
			},
			confirmImport(){
				this.$refs.upload.submit()
			},
			closeUpload(){
				this.importVisible=false
				this.$refs.upload.clearFiles()
			},
			async upload(param){
				var formData=new FormData()
				formData.append('file',param.file)
				var res=await this.$request.importExcel(formData,{category:2})
				param.onSuccess(res)
			},
			beforeUpload(){
				this.tipText='上传中...'
			},
			uploadError(){
				this.tipText='上传失败'
			},
			uploadSuccess(res, file, fileList){
				if(!res){
					return
				}
				if(res.code==0){
					this.tipText=''
					this.msgSuccess('上传成功')
					this.getData()
					this.closeUpload()
				}else{
					console.log(res)
					this.tipText=res.msg
				}
			},
			batchGet(){
				var list=this.$refs.table.selection
				if(!list.length){
					this.msgError('请先选择数据')
					return
				}
				var flag=true
				var ids=[]
				list.forEach(item=>{
					ids.push(item.customeruid)
				})
				this.network=true
				this.$request.batchGetMaterial({
					customeruids:ids.join(',')
				}).then(res=>{
					if(res.code==0){
						this.msgSuccess('操作成功')
						this.search()
					}
					else{
						this.msgError(res.msg)
					}
					this.network=false
				})
			},
			batchDistribute() {
				this.batchFlag=true
				var list=this.$refs.table.selection
				if(!list.length){
					this.msgError('请先选择数据')
					return
				}
				var flag=true
				var ids=[]
				list.forEach(item=>{
					if(item.owenerid){
						flag=false
					}
					ids.push(item.customeruid)
				})
				if(!flag){
					this.msgError('已分配渠道的线索不可再分配')
					return
				}
				this.customeruids=ids.join(',')
				this.channelIndex=''
				this.distributeVisible=true
			},
			confirmBatchDistribute(){
				if(this.network){
					return
				}
				if(!this.channelIndex&&this.channelIndex!==0){
					this.msgError('请选择所属渠道')
					return
				}
				this.network=true
				this.$request.batchDistributeMaterial({
					channelid:this.distributeObj.channelid,
					channelname:this.distributeObj.channelname,
					customeruids:this.customeruids
				}).then(res=>{
					if(res.code==0){
						this.distributeVisible=false
						this.msgSuccess('操作成功')
						this.getData()
					}
					else{
						this.msgError(res.msg)
					}
					this.network=false
				})
			},
			edit(obj) {
				this.obj=obj
				this.editVisible=true
			},
			distribute(obj) {
				this.batchFlag=false
				this.channelIndex=''
				this.distributeObj.customeruid=obj.customeruid
				this.distributeObj.channelname=obj.ownername
				this.distributeObj.channelid=obj.owenerid
				this.channelList.forEach((item,index)=>{
					if(item.channelid==obj.owenerid){
						this.channelIndex=index
					}
				})
				
				this.distributeVisible=true
			},
			channelChange(){
				if(this.channelIndex||this.channelIndex===0){
					this.distributeObj.channelname=this.channelList[this.channelIndex].channelname
					this.distributeObj.channelid=this.channelList[this.channelIndex].channelid
				}
			},
			confirmDistribute(){
				if(this.network){
					return
				}
				if(!this.channelIndex&&this.channelIndex!==0){
					this.msgError('请选择所属渠道')
					return
				}
				this.network=true
				this.$request.distributeMaterial(this.distributeObj)
				.then(res=>{
					if(res.code==0){
						this.distributeVisible=false
						this.msgSuccess('操作成功')
						this.getData()
					}
					else{
						this.msgError(res.msg)
					}
					this.network=false
				})
			},
			get(customeruid){
				if(this.network){
					return
				}
				console.log(customeruid)
				this.network=true
				this.$request.getMaterial({
					customeruid:customeruid
				}).then(res=>{
					if(res.code==0){
						this.msgSuccess('操作成功')
						this.getData()
					}else{
						this.msgError(res.msg)
					}
					this.network=false
				})
			},
		}
	}
</script>
<style scoped lang="scss">
	.page {
		.head {
			border-bottom: 10px solid #f5f5f5;
			padding: 0 20px;
		}
		.search-wrap {
			padding: 24px 10px 8px;
			.el-button {
				img,
				i {
					margin-right: 3px;
				}
				i {
					font-size: 12px;
					font-weight: bold;
				}
			}
		}
		>>>.el-table {
			th {
				>.cell {
					padding-left: 6px;
					padding-right: 6px;
					text-align: center;
				}
			}
			td {
				>.cell {
					padding-left: 4px;
					padding-right: 4px;
					text-align: center;
					font-size: 12px;
					line-height: 16px;
				}
			}
		}
	}
	
	.btn-inner {
		margin-top: -8px;
		margin-left: -8px;
		.btn {
			width: 24px;
			height: 24px;
			margin-left: 8px;
			margin-top: 8px;
			text-align: center;
			line-height: 24px;
			color: #fff;
			font-weight: bold;
			font-size: 14px;
			cursor: pointer;
			float: left;
			border-radius: 2px;
			position: relative;
			img {
				width: 100%;
				height: 100%;
			}
		}
	}
	
	>>>.el-dialog__header {
		padding: 16px 20px 16px 30px;
		text-align: left;
		font-weight: bold;
	}
	
	>>>.el-dialog--center .el-dialog__body{
		padding: 0 16px 10px;
		.dialog-content {
			border-top: 1px solid #eee;
			border-bottom: 1px solid #eee;
			padding: 20px 10px;
			>.clear {
				margin-bottom: 20px;
				&:last-child{
					margin-bottom: 0;
				}
			}
			.form-item {
				margin-bottom: 0px;
				float: left;
				.form-item-title {
					width: 100px;
				}
				.form-item-content {
					width: 180px;
					.template-download{
						text-decoration: underline;
						color: #409EFF;
					}
				}
			}
		}
	}
</style>